package com.xiaoqiudong.forum.controller;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import com.xiaoqiudong.forum.config.AppConfig;
import com.xiaoqiudong.forum.exception.ApplicationException;
import com.xiaoqiudong.forum.model.Article;
import com.xiaoqiudong.forum.model.Board;
import com.xiaoqiudong.forum.model.User;
import com.xiaoqiudong.forum.service.IArticleService;
import com.xiaoqiudong.forum.service.IBoardService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-26
 * Time:10:22
 */
@RestController
@Slf4j
@RequestMapping("/article")
@Tag(name = "文章接口")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /**
     * 发布新帖
     * @param title 标题
     * @param boardId 板块Id
     * @param content 类容
     * @return
     */
    @PostMapping("/create")
    @Operation(description = "发布新帖")
    public AppResult create(HttpServletRequest request,
                            @Parameter(name = "boardId",description = "板块Id") @Nonnull Long boardId,
                            @Parameter(name = "title",description = "文章标题") @Nonnull String title,
                            @Parameter(name = "content",description = "文章类容") @Nonnull String content){
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //板块校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);

        //发布
        articleService.create(article);
        return AppResult.success();
    }

    @Operation(description = "贴子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@Parameter(name = "boardId",description = "板块id") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles;
        if (boardId == null){
            //板块id 为空
            articles = articleService.selectAll();
            log.info("查询所有信息");
        }else {
            articles = articleService.selectAllByBoardId(boardId);
            log.info("根据板块id,查询所有信息");
        }
        //结果为空
        if (articles == null){
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @GetMapping("/detail")
    @Operation(description = "根据帖子id查询消息星系")
    public AppResult<Article> getDetail(HttpServletRequest request,
                                        @Parameter(name = "id",description = "帖子id") @RequestParam("id") @Nonnull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //获取帖子详情
        Article article = articleService.selectDetailById(id);
        if (article == null){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if (user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    /**
     * 修改帖子
     * @param id 帖子id
     * @param title 标题
     * @param content 内容
     * @return
     */
    @PostMapping("/modify")
    @Operation(description = "修改帖子")
    public AppResult modify(HttpServletRequest request,
                            @Parameter(name = "id" ,description = "贴子id") @RequestParam("id") @Nonnull Long id,
                            @Parameter(name = "title" ,description = "标题") @RequestParam("title") @Nonnull String title,
                            @Parameter(name = "content" ,description = "内容") @RequestParam("content") @Nonnull String content){
        //获取登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //用户是否禁言
        if (user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //查询贴子是否有效
        Article article = articleService.selectById(id);
        if (article == null ){
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是不是作者,权限问题
        if (user.getId() != article.getUserId() ){
            log.info(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }
        //校验通过允许修改
        articleService.modify(id,title,content);
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");
        return AppResult.success();
    }


    /**
     * 点赞
     * @param id 帖子id
     * @return
     */
    @PostMapping("/thumbsUp")
    @Operation(description = "点赞")
    public AppResult thumbsUp(HttpServletRequest request,
                              @Parameter(name = "id",description = "帖子id") @RequestParam("id") @Nonnull Long id){
        HttpSession session = request.getSession(false);
        //用户是否被禁言
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //校验帖子
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @Operation(description = "删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                                @Parameter(name = "id",description = "帖子id") @RequestParam("id") @Nonnull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            //用户被禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //检验帖子状态
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //当前用户不是作者
        if(user.getId() != article.getUserId()){
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        log.info("删除成功");
        return AppResult.success();
    }


    @Operation(description = "获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @Parameter(name = "userId" ,description = "用户Id") @RequestParam(value = "userId",required = false) Long userId){
        //如果UserId为空，那么从session中获取当前登录的用户Id
        if (userId == null){
            HttpSession session = request.getSession(false);
            User user =(User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectAllByUserId(userId);
        return AppResult.success(articles);
    }
}
